<template>
  <a-card :bordered="false" style="height: 100%; overflow-y: auto;">
    <!-- <a-row><h3 style="font-weight:bold">对账管理</h3></a-row> -->
    <a-form-model
      ref="queryForm"
      class="query-form"
      layout="inline"
      :model="queryParam"
      @keyup.enter="loadData(1)"
    >
      <a-form-model-item class="form-item" label="订单时间" prop="selectedTime">
        <a-range-picker
          allowClear
          v-model="queryParam.selectedTime"
          :ranges="{ '今天': [moment(), moment()], '本月': [moment(), moment().endOf('month')] }"
          show-time
          format="YYYY/MM/DD HH:mm:ss"
          @change="onChange"
        />
      </a-form-model-item>
      <a-form-model-item>
        <a-button-group style="margin-right:12px">
          <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
          <a-button @click="searchReset" icon="reload">重置</a-button>
        </a-button-group>
        <a-button type="primary" @click="exportData" :loading="exporting" icon="export" style="margin-right:12px">导出</a-button>
      </a-form-model-item>
    </a-form-model>
    <a-spin :spinning="loading">
      <a-table
        bordered
        :columns="columns"
        :pagination="ipagination"
        :data-source="dataSource"
        :rowKey="(record,index)=>index"
        style="margin-top: 36px"
        @change="handleTableChange"
      >
      </a-table>
    </a-spin>
  </a-card>
</template>
<script>
import { mapState } from 'vuex'
import moment from 'moment'
import { axios } from '@/utils/request'
import modelDetail from './components/modelDetail.vue'
import { downloadBlobFile } from '@/utils/functions'

export default {
  name: 'StateMent',
  data () {
    const self = this
    return {
      queryParam: {
        selectedTime: undefined,
        startCreateTime: '',
        endCreateTime: ''
      },
      loading: false,
      exporting: false,
      state: 'add',
      exportType: 0,
      dataSource: [],
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30', '50', '100'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      columns: [
        {
          title: '订单创建时间',
          dataIndex: 'createTime',
          align: 'center',
          customRender: text => text ? self.timeFormat(text, 'yyyy-mm-dd hh:mm:ss') : '-'
        },
        {
          title: '订单编号',
          dataIndex: 'orderId',
          align: 'center'
        },
        {
          title: 'TPSM订单编号',
          dataIndex: 'tspOrderId',
          align: 'center'
        },
        {
          title: '第三方订单号',
          dataIndex: 'orderNo',
          align: 'center'
        },

        {
          title: '第三方平台来源',
          dataIndex: 'supplierName',
          align: 'center'
        },
        {
          title: '第三方平台用户ID',
          dataIndex: 'userId',
          align: 'center'
        },
        {
          title: '套餐内容',
          dataIndex: 'softServerName',
          align: 'center'
        },
        {
          title: '数量',
          dataIndex: 'amount',
          align: 'center'
        },
        {
          title: '充值状态',
          dataIndex: 'status',
          align: 'center',
          width: 150,
          customRender: text => text ? ['未激活','充值成功','充值失败'][text] : '-'
        }
      ]
    }
  },
  computed: {
    ...mapState({
      queryParams: (state) => state.orderManagement.queryParams
    })
  },
  components: {
    modelDetail
  },
  methods: {
    timeFormat (time, format) {
      const TIME = new Date(time)
      const DEL = data => (data < 10 ? '0' + data : data)
      const TMOBJ = {
        yyyy: TIME.getFullYear(),
        yy: TIME.getFullYear() % 100,
        MM: DEL(TIME.getMonth() + 1),
        M: TIME.getMonth() + 1,
        dd: DEL(TIME.getDate()),
        d: TIME.getDate(),
        hh: DEL(TIME.getHours()),
        h: TIME.getHours(),
        mm: DEL(TIME.getMinutes()),
        m: TIME.getMinutes(),
        ss: DEL(TIME.getSeconds()),
        s: TIME.getSeconds()
      }
      const reg1 = /(y+.)m+(.d+)/gi
      const reg2 = /(h+.)m+(.s+)/gi
      format = format.toLowerCase().replace(reg1, '$1MM$2').replace(reg2, '$1mm$2')
      for (const i in TMOBJ) {
        format = format.replace(i, TMOBJ[i])
      }
      return format
    },
    searchReset () {
      this.$refs.queryForm.resetFields()
      // this.queryParam.createTime = ['date', 'date']
      console.log(this.queryParam.createTime)
      this.onChange('', [])
      this.queryParam.selectedTime = []
      this.loadData(1)
    },
    searchQuery () {
      console.log(this.queryParam)
      this.loadData(1)
    },
    filterObj (obj) {
      if (!(typeof obj === 'object')) {
        return
      }
      for (const key in obj) {
        if ((obj.hasOwnProperty(key) &&
          (obj[key] == null || obj[key] === undefined || obj[key] === '')) ||
          key.indexOf('selectedTime') > -1) {
          delete obj[key]
        }
      }
      return obj
    },
    getQueryParams () {
      const param = Object.assign({}, this.queryParam)
      param.pageNo = this.ipagination.current
      param.pageSize = this.ipagination.pageSize
      return this.filterObj(param)
    },
    loadData (arg) {
      if (arg === 1) {
        this.ipagination.current = 1
      }
      this.loading = true
      const params = this.getQueryParams()
      this.rowSelected = []
      axios.get('/service-sale/merchant/member/list', { params: params }).then(data => {
        this.loading = false
        console.log(data)
        this.ipagination.total = data.totalCount
        this.dataSource = data.data
      })
    },
    handleTableChange (pagination) {
      console.log(pagination)
      this.ipagination = pagination
      this.loadData()
    },
    moment,
    onChange (dates, dateStrings) {
      console.log(dateStrings)
      this.queryParam.startCreateTime = dateStrings[0]
      this.queryParam.endCreateTime = dateStrings[1]
    },
    exportData () {
      console.log(this.exportType)
      this.exporting = true
      this.queryParam.pageNo = 1
      this.queryParam.pageSize = 1000000
      const params = this.getQueryParams()
      params.pageNo = 1
      params.pageSize = 1000000
      const exportParam = this.exportType === 1 ? { tspOrderId: this.rowSelected.join(',') } : params
      axios({
        url: '/service-sale/merchant/exportMember',
        method: 'get',
        params: exportParam,
        responseType: 'blob'
      }).then(res => {
        downloadBlobFile(res, 'system-log.xlsx')
      }).finally(() => {
        this.exporting = false
        this.$message.success('导出成功')
      })
    }
  },
  mounted () {
    this.loadData(1)
  }
}
</script>
<style lang="less" scoped>
</style>
